package com.example.service.impl;

import ch.qos.logback.classic.Logger;
import com.example.entity.PointDefend;
import com.example.entity.SpotCheckPlan;
import com.example.entity.SpotObjectCensus;
import com.example.entity.SpotObjectPlan;
import com.example.entity.authority.SystemUser;
import com.example.mapp.*;
import com.example.service.MessageNoticeService;
import com.example.service.SpotObjectPlanService;
import com.example.util.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 实施对象
 */
@Service
public class SpotObjectPlanServiceImpl implements SpotObjectPlanService{

	private final static Logger logger = (Logger) LoggerFactory.getLogger(SpotObjectPlanServiceImpl.class);

	@Autowired
	private SpotObjectPlanMapp spotObjectPlanMapp;

	// 用户Map
	@Autowired
	private SysUserMapp sysUserMapp;

	// 发送通知
	@Autowired
	private MessageNoticeService messageNoticeService;

	// 计划
	@Autowired
	private SpotCheckPlanMapp spotCheckPlanMapp;

	// 检测项
	@Autowired
	private SpotCheckItemMapp spotCheckItemMapp;

	@Autowired
	private Environment environment;

	@Autowired
	private PointFlowMapp pointFlowMapp;

	/**
	 * 查询某一段时间内得维保信息
	 * spotCheckPlan
	 * @return
	 */

	@Override
	public Map<String, Object> findList(SpotObjectPlan spotObjectPlan) {
		String message = "查询成功";
		Map<String, Object> map = new HashMap<String, Object>();
		try{
			Page<SpotCheckPlan> page = PageHelper.startPage(spotObjectPlan.getCurrentPage(), spotObjectPlan.getPageSize());
			List<SpotObjectPlan> list = spotObjectPlanMapp.findList(spotObjectPlan);
			map.put("list", list);
			map.put("total", page.getTotal());
		}catch (Exception e){
			logger.error(e.getMessage());
			message="查询失败";
			return ResultUtil.returnError(message + e.getMessage(),spotObjectPlan);
		}
		return ResultUtil.returnSuccess(message, map);
	}

	/**
	 * 新增数据
	 * @param
	 * @return
	 */
	@Override
	public Map<String, Object> insert(SpotObjectPlan spotObjectPlan) {
		String message = "添加成功";
		Map<String, Object> resultMap = new HashMap<>();
		try {
			long planId = spotObjectPlan.getPlanId();

			// 实施对象Id
			List<String> planList = Arrays.asList(spotObjectPlan.getImplementObjectId().split(","));
			if (planList != null && planList.size() > 0) {
				for (String object : planList) {
					//同一计划下、对多次实施对象重复判断
					SpotObjectPlan op = new SpotObjectPlan();
					op.setImplementObjectId(object);
					op.setPlanId(planId);
					List spList = spotObjectPlanMapp.findList(op);
					if(spList != null && spList.size() > 0){
						continue;
					}

					SpotObjectPlan objectPlan = new SpotObjectPlan();
					objectPlan.setPlanId(planId);

					// 通过实施对象Id，寻找实施对象名称
					SystemUser systemUser = sysUserMapp.queryById(object);
					objectPlan.setImplementObjectId(object);
					objectPlan.setImplementObject(systemUser.getUserName());
					objectPlan.setHeadMan(spotObjectPlan.getHeadMan());
					objectPlan.setCreateBy(spotObjectPlan.getCreateBy());

					objectPlan.setCreateDate(DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
					objectPlan.setDelFlag("1");
					objectPlan.setCheckRecord("0");
					spotObjectPlanMapp.insert(objectPlan);
				}
			}

		}catch (Exception e){
			logger.error(e.getMessage());
			message = "添加失败";
			return ResultUtil.returnError(message + e.getMessage(), spotObjectPlan);
		}finally {
			// 获取缓存
			PointDefendInfoCache infoCache = new PointDefendInfoCache();
			PointDefend defend = infoCache.getKeyByValue("maintenance_check_plan");

			// 获取当前用户，计算积分
			Map<String, Object> maps = pointFlowMapp.findUserInfoByUserId(spotObjectPlan.getUserId());
			long mark = (long) maps.get("mark");
			int round = (int) (mark + defend.getMark());
			// 更新用户信息总积分
			String userId = maps.get("userId").toString();
			int i1 = pointFlowMapp.updateMark(round, userId);

			String userName = maps.get("userName").toString();
			String partyName = maps.get("partyName").toString();
			SystemPointUtil.insertFlow(pointFlowMapp, i1, defend, round, userName, partyName, "新增维保计划");
		}
		return ResultUtil.returnSuccess(message, resultMap);
	}

	/**
	 * 修改信息
	 * @param map
	 * @return
	 */
	@Override
	public Map<String, Object> update(Map map) {

		String message = "新增成功";
		List<SpotObjectPlan> list = new ArrayList<>();
		try {
			// 获取的是任务工单里的任务Id
			String ids = (String) map.get("updateId");
			List<String> idList = Arrays.asList(ids.split(","));

			// 此时的checkMan对应的是当前用户的Id,通过用户Id找checkMan
			Integer userId = (Integer) map.get("checkMan");
			String checkMan = sysUserMapp.queryById(String.valueOf(userId)).getUserName();

			for (String id : idList) {
				SpotObjectPlan spotObjectPlan = new SpotObjectPlan();
				spotObjectPlan.setId(Long.valueOf(id));
				spotObjectPlan.setCheckMan(checkMan);
				spotObjectPlan.setUserId(Long.valueOf(userId));
				spotObjectPlanMapp.update(spotObjectPlan);
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			message = "新增失败";
			return ResultUtil.returnError(message + e.getMessage(), null);
		}
		return ResultUtil.returnSuccess(message, list);
	}
	/**
	 * 批量删除
	 * @param
	 */
	@Override
	public Map<String,Object> delete(Map map)  {
		String message = "删除成功";
		Map<String, Object> resultMap = new HashMap<>();
		try {
            if (map != null && map.size() > 0) {
                String ids = (String) map.get("ids");
                List<String> idList = Arrays.asList(ids.split(","));
                for (String id : idList) {
                    spotObjectPlanMapp.delete(id);
                }
            }
		}catch (Exception e){
			logger.error(e.getMessage());
			message = "删除失败";
			return ResultUtil.returnError(message + e.getMessage(), null);
		}
		return ResultUtil.returnSuccess(message, resultMap);
	}

	/**
	 * 批量发送通知
	 * @param map
	 * @return
	 */
	@Override
	public Map<String, Object> sendMessage(Map map) {
		String message = "发送成功";
		try{
			// 计划列表Id
			String planId = (String) map.get("planId");

			// 获取发送用户的Id
			String userIds = (String) map.get("userIdList");
			List<String> userIdList = Arrays.asList(userIds.split(","));

			// 获取单位Id
			Integer parentId = (Integer) map.get("parentId");

			// 封装数据
			Map parm = new HashMap();
			parm.put("id",parentId);
			parm.put("userIdList",userIdList);
			parm.put("sendUserId",userIds);
			parm.put("content","您收到了维保计划通知，请尽快前去抽查，完成任务工单！");
			parm.put("title","维保质量检查");
			Map<String,Object> result = messageNoticeService.batchMsg(parm);

			// 定义返回状态
			Integer status = 0;

			Iterator it = result.keySet().iterator();
			while (it.hasNext()) {
				String in = it.next()+"";
				if ("status".equals(in)) {
					status = (Integer) result.get(in);
				}
			}

			if (status == 200) {
				//修改计划的发送通知字段
				spotCheckPlanMapp.updateIsSendMessage(planId);
			}
		}catch (Exception e){
			logger.error(e.getMessage());
			message="发送失败";
			return ResultUtil.returnError(message + e.getMessage(),null);
		}
		return ResultUtil.returnSuccess(message, null);
	}



	// 导出excel
	@Override
	public Map<String, Object> exportExcelObj(Map map) {
		String message = "查询成功";
		Map<String, Object> result = new HashMap<>();

		try {
			// 通过查询的计划Id获取检测项
            List<HashMap<String, Object>> itemList  = (List<HashMap<String, Object>>) map.get("table");

			//如果查询结果不为空，则创建表格，否则不创建
			if (itemList != null && itemList.size() > 0) {
				// 1.获取保存路径，不存在则创建
				String tableName = "维保质量检查统计表";//表名；

				// 创建 表头
				String[] tableN = {"计划名称","被检查人","检查人","检查结论","检查时间","设备Id"};

                String[] tableE = {"planName","implementObject","checkMan","resultEvaluate","createDate","elevatorId"};

				List<String> tablelist = Arrays.asList(tableN);

                List<String> tablelistEc = Arrays.asList(tableE);


                String path = environment.getProperty("upload", String.class);

                result = ExportExcelUtil.writeExcel(tableName, tablelist, tablelistEc, itemList, path);
            }
		}catch (Exception e) {
			logger.error(e.getMessage());
			return ResultUtil.returnError(e.getMessage(), null);
		}
		return ResultUtil.returnSuccess(message, result);
	}

	/**
	 * app端查询维保记录
	 * @param spotObjectPlan
	 * @return
	 */
	@Override
	public Map<String, Object> findRecordApp(SpotObjectPlan spotObjectPlan) {

		String message = "查询成功";
		List<Map<String,Object>> resultList = new ArrayList<>();
		try {
			// 通过用户Id查询计划Id
			resultList = spotObjectPlanMapp.findRecordApp(spotObjectPlan);
		} catch (Exception e) {
			logger.error(e.getMessage());
			message = "查询失败";
			return ResultUtil.returnError(message + e.getMessage(), null);
		}
		return ResultUtil.returnSuccess(message, resultList);
	}

	/**
	 * 维保质量统计
	 * @param map
	 * @return
	 */
	@Override
	public Map<String, Object> spotObjectCensus(Map map) {
		String message = "查询成功";
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			// 通过用户Id查询计划Id
			int currentPage = (int) map.get("currentPage");
			int pageSize = (int) map.get("pageSize");
			Page<Object> page = PageHelper.startPage(currentPage, pageSize);
			List<Map<String, Object>> resultList = spotObjectPlanMapp.spotObjectCensus(map);
			resultMap.put("list", resultList);
			resultMap.put("total", page.getTotal());
		} catch (Exception e) {
			logger.error(e.getMessage());
			message = "查询失败";
			return ResultUtil.returnError(message + e.getMessage(), null);
		}
		return ResultUtil.returnSuccess(message, resultMap);
	}

	/**
	 * app端查询已完成维保记录
	 * @param spotObjectPlan
	 * @return
	 */
	@Override
	public Map<String, Object> queryFinishRecordApp(SpotObjectPlan spotObjectPlan) {

		String message = "查询成功";

		List<Map<String, Object>> list = new ArrayList<>();
		try {
			// 获取已完成维保数据
			List<Map<String, Object>> finishList = spotObjectPlanMapp.findRecordApp(spotObjectPlan);
			if (finishList != null && finishList.size() > 0) {
				for (Map<String, Object> param : finishList) {
					// 获取计划名称
					String planName = (String) param.get("planName");

					List<Map<String, Object>> finishs = spotObjectPlanMapp.getFinishItem(param);
					Map<String, List<Map<String, Object>>> parammap = new HashMap<>();

					for (Map<String, Object> objectMap : finishs) {
						String elevatorId = (String) objectMap.get("elevatorId");

						Map<String, Object> stringObjectList = new HashMap<>();
						String picUrl = (String) objectMap.get("picUrl");

						List<String> split = new ArrayList<>();
						if (StringUtil.isNotBlank(picUrl)) {
							split = Arrays.asList(picUrl.split(","));

						}
						stringObjectList.put("picUrl", split);
						objectMap.put("result", stringObjectList);


						if (parammap.containsKey(elevatorId)) {
							parammap.get(elevatorId).add(objectMap);
						} else {
							List<Map<String, Object>> mapList = new ArrayList<>();
							mapList.add(objectMap);
							parammap.put(elevatorId, mapList);
						}
					}

					Iterator it = parammap.keySet().iterator();
					while (it.hasNext()) {
						Object objName = it.next();
						Map<String, Object> resultMap = new HashMap<>();
						// 计划名称
						resultMap.put("planName", planName);
						// 设备Id
						resultMap.put("elevatorId", objName);

						resultMap.put("project", parammap.get(objName));

						list.add(resultMap);
					}
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			message = "查询失败";
			return ResultUtil.returnError(message + e.getMessage(), null);
		}
		return ResultUtil.returnSuccess(message, list);
	}

	/**
	 * 维保质量抽查统计详情
	 * @param map
	 * @return
	 */
	@Override
	public Map<String, Object> queryPlanDetails(Map map) {
		String message = "查询成功";
		List<Map<String,Object>> resultList = new ArrayList<>();
		try {
			// 通过用户Id查询计划Id
			SpotObjectCensus objectCensus = new SpotObjectCensus();
			objectCensus.setElevatorId((String) map.get("elevatorId"));
			objectCensus.setPlanId(Long.valueOf((Integer) map.get("planId")));
			objectCensus.setImplementObject((String) map.get("implementObject"));
			objectCensus.setCheckMan((String) map.get("checkMan"));

			resultList = spotObjectPlanMapp.queryPlanDetails(objectCensus);
		} catch (Exception e) {
			logger.error(e.getMessage());
			message = "查询失败";
			return ResultUtil.returnError(message + e.getMessage(), null);
		}
		return ResultUtil.returnSuccess(message, resultList);
	}

	@Override
	public List<SpotObjectCensus> exportExcelClown(SpotObjectCensus spotObjectCensus) {

		List<SpotObjectCensus> list = spotObjectPlanMapp.exportExcelClown(spotObjectCensus);

		return list;
	}

	// 导出记录表

	//合并单元格
	private void mergeRegionAndSetWidth(XSSFSheet sheet,int colNum) {
		sheet.addMergedRegion(new CellRangeAddress(0, 0, 0,colNum));
	}
}
